package com.weme.common.fragment

import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.weme.common.base.BaseFragment
import com.weme.common.databinding.FragmentLookBigBinding
import com.weme.common.util.*
import com.weme.common.viewmodel.LookBigImgViewMode

class LookBigImgFragment : BaseFragment<FragmentLookBigBinding, LookBigImgViewMode>() {
    companion object {
        private const val ARG_TYPE = "arg_type"
        private const val ARG_URL = "arg_url"
        private const val ARG_MY = "arg_my"
        fun newInstance(type: Int, url: String,isMy:Boolean): LookBigImgFragment {
            val fragment = LookBigImgFragment()
            val args = Bundle()
            args.putInt(ARG_TYPE, type)
            args.putString(ARG_URL, url)
            args.putBoolean(ARG_MY,isMy)
            fragment.arguments = args
            return fragment
        }
    }


    private lateinit var player: ExoPlayer
    private var playbackPosition: Long = 0

    override fun startOperate() {
        val type = arguments?.getInt(ARG_TYPE)
        val url = arguments?.getString(ARG_URL)
        val isMy = arguments?.getBoolean(ARG_MY)



        if (type!!.isTypeImg()) {
            mBinding.image.loadImage(url)
            mBinding.playerView.setVisible(false)
            mBinding.imLock.gone()
            mBinding.image.setVisible(true)
        } else {


            if (url != null) {
                if(requireActivity().isVip()||isMy==true){
                    mBinding.image.setVisible(false)
                    mBinding.playerView.setVisible(true)
                    staPlay(url)
                    mBinding.imLock.gone()
                }else{
                    mBinding.image.setVisible(true)
                    mBinding.playerView.setVisible(false)
                    Glide.with(requireContext())
                        .load(url)
                        .sizeMultiplier(0.5f)
                        .override(requireActivity().deviceSize.width, requireActivity().deviceSize.height)
                        .error(com.example.resources.R.mipmap.icon_mine_pic_null)
                        .apply(RequestOptions
                            .placeholderOf(com.example.resources.R.drawable.icon_album_null)
                            .transform(GlideBlurTransformer(20, 2))
                        )
                        .into(mBinding.image)
                    mBinding.imLock.visible()
                    mBinding.imLock.setOnFastClickListener{
                        showToast("跳转订阅商城")
                    }
                }

            } // 创建 ExoPlayer 实例

        }
    }
    @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
    fun staPlay(url: String) {
        player = ExoPlayer.Builder(requireContext()).build()
     //   player.repeatMode = Player.REPEAT_MODE_ONE // 将 ExoPlayer 与 PlayerView 关联
        mBinding.playerView.player = player

        mBinding.playerView.controllerShowTimeoutMs = 0
        mBinding.playerView.controllerHideOnTouch = false
        player.repeatMode = Player.REPEAT_MODE_ONE

        // 创建 MediaSource，用于指定视频的来源（可以是网络地址或本地文件）
        val videoUri: Uri = Uri.parse(url)

        val mediaItem = MediaItem.fromUri(videoUri)
        player.setMediaItem(mediaItem) // 准备播放器
        player.prepare()

        // 恢复播放位置（如果有保存的位置）
        if (playbackPosition > 0) {
            player.seekTo(playbackPosition)
        }
        player.addListener(object : Player.Listener {
            override fun onEvents(player: Player, events: Player.Events) {
                super.onEvents(player, events)

            }

            override fun onPlayerError(error: PlaybackException) {
                super.onPlayerError(error)
                Log.e("tag", error.errorCode.toString() + "" + error.errorCodeName)
            }
        })

        // 开始播放
        player.playWhenReady = true
    }


    override fun onStop() {
        super.onStop()

    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (::player.isInitialized)  player.release()
    }
    fun onPlayerPlay(){
        if (::player.isInitialized)  player.playWhenReady = true
    }
    fun onPlayerStop(){
        if (::player.isInitialized&&requireActivity().isVip())     player.playWhenReady = false
    }




    override fun clickListener() {
    }

    override fun getViewModel(): Class<LookBigImgViewMode> = LookBigImgViewMode::class.java
}